package com.it.romannumber;

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入一个罗马数字字符串: ");
        String roman = scanner.nextLine();
        scanner.close();

        int result = romanToInt(roman);

        if (result == -1) {
            System.out.println("输入的罗马数字无效！");
        } else {
            System.out.println("对应的整数值是: " + result);
        }
    }

    public static int romanToInt(String s) {
        // 定义罗马数字到整数的映射
        int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

        int result = 0;
        int index = 0;

        // 遍历罗马数字字符串
        for (int i = 0; i < s.length(); ) {
            // 检查当前字符是否匹配两个字符的组合
            if (index < symbols.length && s.startsWith(symbols[index], i)) {
                result += values[index];
                i += symbols[index].length(); // 跳过匹配的字符
            } else {
                index++; // 尝试下一个符号
            }
        }

        return result;
    }
}
